package Phase;

import Entities.Scene;
import StateInformation.GameState;
import StateInformation.Life;
import Visitor.GraphicPaintVisitor;
import Visitor.IVisitor;
import Visitor.PaintVisitor;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

public class Renderer extends Thread {

    private ArkanoidPanel arkanoidPanel;
    private Graphics g;
    private Scene scene;
    private boolean stop;
    private GameState gameState;

    public Renderer(ArkanoidPanel arkanoid, Scene scene, GameState gameState) {
        this.arkanoidPanel = arkanoid;
        this.scene = scene;
        stop = false;
        this.gameState = gameState;

    }

    @Override
    public void run() {
        g = arkanoidPanel.getCanvas().getImage().getGraphics();
        while (!stop) {
            try {
                g.clearRect(0, 0, 400, 300);
                IVisitor paintVisitor = new GraphicPaintVisitor(g);
                scene.accept(paintVisitor);

                renderGameState();
                
                arkanoidPanel.repaint();
                Thread.sleep(5);
            } catch (InterruptedException ex) {
                Logger.getLogger(Renderer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void setTerminar(boolean stop) {
        this.stop = stop;
    }

    private void renderGameState() {
        BufferedImage image;
        try {
            image = ImageIO.read(new File("heart_icon.jpg"));
            Graphics graphics = arkanoidPanel.getLifePanel().getImage().getGraphics();
            for (int i = 0; i < gameState.getNumberOfLifes(); i++) {
                graphics.drawImage(image, image.getWidth() * i, 0, null);
            }
        } catch (IOException ex) {
            Logger.getLogger(Life.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        Graphics graphics = arkanoidPanel.getScorePanel().getImage().getGraphics();
        graphics.setColor(Color.black);
        graphics.drawString(gameState.getScore().toString(), 15, 20);
        
        graphics = arkanoidPanel.getTimePanel().getImage().getGraphics();
        if (gameState.getPlayedTime().getTime().getSeconds() < 10) {
            graphics.drawString(gameState.getPlayedTime().getTime().getMinutes() + ":0" + gameState.getPlayedTime().getTime().getSeconds(), 15, 20);
        } else {
            graphics.drawString(gameState.getPlayedTime().getTime().getMinutes() + ":" + gameState.getPlayedTime().getTime().getSeconds(), 15, 20);
        }
    }
}
